package com.example.musiccommunity.UserPage;

import android.animation.ValueAnimator;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.baidu.aip.util.Base64Util;
import com.example.musiccommunity.MainActivity;
import com.example.musiccommunity.ManagerPage.AddNotice;
import com.example.musiccommunity.R;
import com.example.musiccommunity.bean.Remark;
import com.example.musiccommunity.bean.Song;
import com.example.musiccommunity.util.GridAdapter;
import com.example.musiccommunity.util.ImageUtil;
import com.example.musiccommunity.util.MusicController;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.android.material.bottomsheet.BottomSheetDialog;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class PlayMusic extends AppCompatActivity {
    private Toolbar toolbar;
    private ImageView img;
    private TextView name;
    private TextView artist;
    private ImageView remark,download;
    private TextView now;
    private SeekBar progressBar;
    private TextView total;
    private ImageView previous;
    private ImageView play;
    private ImageView next;
    ArrayList<Remark> remarks=new ArrayList<>();

    private MusicController musicController;

    private Handler handler = new Handler();
    private Runnable updateSeekBar;

    BaseAdapter mAdapter = null;
    GridView grid;
    String now_id;
    Bitmap bp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_play_music);

        BitmapDrawable bd = (BitmapDrawable) MainActivity.user.getPic();
        bp = bd.getBitmap();
        bp=ImageUtil.compressImage(bp);
        download= findViewById(R.id.download);
        now_id=getIntent().getStringExtra("id");
        toolbar = findViewById(R.id.toolbar);
        img = findViewById(R.id.img);
        name = findViewById(R.id.name);
        artist = findViewById(R.id.artist);
        remark = findViewById(R.id.remark);
        now = findViewById(R.id.now);
        progressBar = findViewById(R.id.seekbar);
        total = findViewById(R.id.total);
        previous = findViewById(R.id.previous);
        play = findViewById(R.id.play);
        next = findViewById(R.id.next);
        toolbar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        download.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                begin();
            }
        });
        int i=0;
        for (Song s: MainActivity.songs
        ) {
            if(s.getRawResId().equals(getIntent().getStringExtra("id"))){
                name.setText(s.getName()+" - "+s.getArtist());
                artist.setText("来自专辑《"+s.getAlbum()+"》");
                addRecord(s.getStyle(),s.getArtist());
                break;
            }
            i++;
        }

        // 初始化控制器
        musicController = new MusicController(this,MainActivity.songs, i);
        musicController.mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                next.performClick();
            }
        });

        // 设置监听器
        play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int i=musicController.togglePlay();
                if(i==1){
                    play.setImageDrawable(getDrawable(R.drawable.play));
                }else{
                    play.setImageDrawable(getDrawable(R.drawable.pause));
                }
            }
        });
        play.performClick();
        next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                musicController.nextSong();
                Song s=MainActivity.songs.get(musicController.currentPosition);
                name.setText(s.getName()+" - "+s.getArtist());
                artist.setText("来自专辑《"+s.getAlbum()+"》");
                now_id=s.getRawResId();
                addRecord(s.getStyle(),s.getArtist());
                musicController.mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mediaPlayer) {
                        next.performClick();
                    }
                });
            }
        });
        previous.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                musicController.previousSong();
                Song s=MainActivity.songs.get(musicController.currentPosition);
                name.setText(s.getName()+" - "+s.getArtist());
                artist.setText("来自专辑《"+s.getAlbum()+"》");
                now_id=s.getRawResId();
                addRecord(s.getStyle(),s.getArtist());
                musicController.mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mediaPlayer) {
                        next.performClick();
                    }
                });
            }
        });

        progressBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {
                    // 根据进度调整播放位置
                    int duration = musicController.mediaPlayer.getDuration();
                    int newPosition = (int) (((float) progress / 100) * duration);
                    musicController.mediaPlayer.seekTo(newPosition);
                }
            }
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                // 停止自动更新进度条
                handler.removeCallbacks(updateSeekBar);
            }
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                // 恢复自动更新进度条
                handler.post(updateSeekBar);
            }
        });
        // 设置 SeekBar 的最大值
        progressBar.setMax(100);
        // 更新 SeekBar 的进度
        updateSeekBar = new Runnable() {
            @Override
            public void run() {
                if (musicController != null &&  musicController.mediaPlayer!=null && musicController.mediaPlayer.isPlaying()   ) {
                    int currentPosition = musicController.mediaPlayer.getCurrentPosition();
                    int duration = musicController.mediaPlayer.getDuration();

                    // 计算当前进度百分比
                    if (duration > 0) {
                        int progress = (int) (((float) currentPosition / duration) * 100);
                        progressBar.setProgress(progress);
                    }

                    //显示总时长
                    int minute = duration/1000/60;
                    int second = duration/1000%60;
                    String strMinute = "";
                    String strSecond = "";
                    if(minute<10){
                        strMinute = "0"+minute;
                    }else{
                        strMinute = minute + "";
                    }
                    if(second<10){
                        strSecond = "0"+second;
                    }else{
                        strSecond = second + "";
                    }
                    //显示总时长结束
                    total.setText(strMinute+":"+strSecond);
                    //显示播放时长开始
                    minute = currentPosition/1000/60;
                    second = currentPosition/1000%60;
                    if(minute<10){
                        strMinute = "0"+minute;
                    }else{
                        strMinute = minute + "";
                    }
                    if(second<10){
                        strSecond = "0"+second;
                    }else{
                        strSecond = second + "";
                    }
                    now.setText(strMinute+":"+strSecond);
                    //播放时长结束

//                    if(currentPosition>=duration-1){
//                        next.performClick();
//                    }
                }
                handler.postDelayed(this, 100);
            }
        };
        // 开始更新进度条
        handler.post(updateSeekBar);
        remark.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 参数2：设置BottomSheetDialog的主题样式；将背景设置为transparent
                BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(PlayMusic.this, R.style.BottomSheetDialog);
                View bottomView = LayoutInflater.from(PlayMusic.this).inflate(R.layout.layout_bottom_click_comment, null);
                bottomSheetDialog.setContentView(bottomView);
                bottomSheetDialog.setCanceledOnTouchOutside(true);

                // 获取 BottomSheetBehavior
                View bottomSheet = bottomSheetDialog.findViewById(com.google.android.material.R.id.design_bottom_sheet);
                if (bottomSheet != null) {
                    BottomSheetBehavior<View> behavior = BottomSheetBehavior.from(bottomSheet);

                    // 禁用滑动关闭
                    behavior.setHideable(false);
                    // 禁用拖拽手势
                    behavior.setDraggable(false);


                    // 设置动画时长（单位：毫秒）
                    behavior.setHideable(true);
                    behavior.setPeekHeight(0);
                    behavior.setState(BottomSheetBehavior.STATE_EXPANDED);
                    // 使用 ValueAnimator 控制动画
                    ValueAnimator animator = ValueAnimator.ofInt(0, 100);
                    animator.setDuration(200); // 1秒动画
                    animator.addUpdateListener(animation -> {
                        float fraction = animation.getAnimatedFraction();
                        bottomSheet.setTranslationY((1 - fraction) * bottomSheet.getHeight());
                    });
                    animator.start();
                }
                bottomSheetDialog.show();
                EditText text;
                RatingBar rating;
                Button save;

                grid = bottomView.findViewById(R.id.grid);
                text = bottomView.findViewById(R.id.text);
                rating = bottomView.findViewById(R.id.rating);
                save = bottomView.findViewById(R.id.save);

                setRemark();
                save.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if(text.getText().toString().equals("") ||  rating.getRating()<=0.0){
                            Toast.makeText(getBaseContext(), "请输入评论并进行星级评分！", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        byte[] bytes1 = ImageUtil.getBytesByBitmap(bp);
                        String image1 = Base64Util.encode(bytes1);
                        String url=MainActivity.ip+"/remark/add";
                        StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                                new Response.Listener<String>() {
                                    @Override
                                    public void onResponse(String response) {
                                        // 处理响应
                                        String s=response;
                                        Log.d("***********",s.toString());
                                        if(s.toString().equals("success")){
                                            Toast.makeText(PlayMusic.this, "评论成功", Toast.LENGTH_SHORT).show();
                                            setRemark();
                                            text.setText("");
                                        }else{
                                            Toast.makeText(PlayMusic.this, "评论失败!", Toast.LENGTH_SHORT).show();
                                        }
                                    }
                                },
                                new Response.ErrorListener() {
                                    @Override
                                    public void onErrorResponse(VolleyError error) {
                                        // 处理错误
                                        Log.d("--------",error.getMessage().toString());
                                        Toast.makeText(PlayMusic.this, "评论失败", Toast.LENGTH_SHORT).show();
                                    }
                                }) {
                            @Override
                            protected Map<String, String> getParams() {
                                Map<String, String> params = new HashMap<>();
                                params.put("song_id", now_id);
                                params.put("user", MainActivity.user.getName());
                                params.put("txt",text.getText().toString());
                                params.put("rate", rating.getRating()+"");
                                params.put("like_num", "0");
                                params.put("avatarBase64", image1); // 将 Base64 字符串作为参数传递
                                return params;
                            }
                        };
                        MainActivity.requestQueue.add(stringRequest);

                    }
                });

            }
        });
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (musicController != null) {
            musicController.release();
        }
    }
    void setRemark( ){
        String url= MainActivity.ip+"/remark/get?song_id="+now_id;
        System.out.println(url);
        StringRequest stringRequest=new StringRequest(Request.Method.POST,url, new com.android.volley.Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                //s = new String(s.getBytes("ISO-8859-1"), "UTF-8");
                //Log.d("user***********user",s.toString());
                if(s==null || s.equals("")){
                    Toast.makeText(getBaseContext(), "获取数据失败", Toast.LENGTH_SHORT).show();
                }
                else{
                    remarks =new ArrayList<>();
                    JSONObject jsonObject = null;
                    try {
                        JSONArray jsonArray = new JSONArray(s);
                        for (int i=0;i<jsonArray.length();i++){
                            jsonObject = jsonArray.getJSONObject(i);
                            String id = jsonObject.get("id").toString();
                            String img=jsonObject.get("img").toString();
                            Bitmap bit = ImageUtil.base64ToBitmap(img);
                            Remark n=new Remark(id,jsonObject.get("song_id").toString(),
                                    jsonObject.get("user").toString(),
                                    new BitmapDrawable(bit),
                                    jsonObject.get("txt").toString(),
                                    jsonObject.get("rate").toString(),
                                    jsonObject.get("like_num").toString() );
                            remarks.add(n);
                        }
                        Collections.reverse(remarks);
                        mAdapter = new GridAdapter<Remark>(remarks, R.layout.list_remark) {
                            @Override
                            public void bindView(ViewHolder holder, Remark obj) {
                                holder.setText(R.id.name, obj.getUser());
                                holder.setText(R.id.txt, obj.getTxt());
                                holder.setText(R.id.like_num, obj.getLike_num());
                                holder.setRatingBar(R.id.rating, Float.parseFloat(obj.getRate() ));
                                holder.setImageSrc(R.id.img,obj.getUser_img());
                                holder.setOnClickListener(R.id.like, new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        int ii=Integer.parseInt(obj.getLike_num());
                                        int position=holder.getItemPosition();
                                        ii++;
                                        int finalIi = ii;
//                                        System.out.println(obj.getId());
//                                        System.out.println(finalIi);
//                                        System.out.println(remarks.get(holder.getItemPosition()));
                                        String url=MainActivity.ip+"/remark/update";
                                        StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                                                new Response.Listener<String>() {
                                                    @Override
                                                    public void onResponse(String response) {
                                                        String s=response;
                                                        if(s.toString().equals("success")){
                                                            //Toast.makeText(PlayMusic.this, "评论成功", Toast.LENGTH_SHORT).show();
                                                            holder.setText(R.id.like_num, finalIi +"");
                                                            remarks.get(position).setLike_num(finalIi +"");
                                                            mAdapter.notifyDataSetChanged();
                                                        }else{
                                                            //Toast.makeText(PlayMusic.this, "点赞失败!", Toast.LENGTH_SHORT).show();
                                                        }
                                                    }
                                                },
                                                new Response.ErrorListener() {
                                                    @Override
                                                    public void onErrorResponse(VolleyError error) {
                                                        // 处理错误
                                                        Log.d("--------",error.getMessage().toString());
                                                        //Toast.makeText(PlayMusic.this, "评论失败", Toast.LENGTH_SHORT).show();
                                                    }
                                                }) {
                                            @Override
                                            protected Map<String, String> getParams() {
                                                Map<String, String> params = new HashMap<>();
                                                params.put("id", obj.getId());
                                                params.put("like_num", finalIi +"");
                                                return params;
                                            }
                                        };
                                        MainActivity.requestQueue.add(stringRequest);
                                    }
                                });
                            }
                        };
                        grid.setAdapter(mAdapter);

                    } catch (JSONException e) {
                        System.out.println(e.toString());
                        throw new RuntimeException(e);
                    }
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Log.d("--------",volleyError.toString());
                Toast.makeText(getBaseContext(), "获取数据失败", Toast.LENGTH_SHORT).show();
            }
        });//字符串
        MainActivity.requestQueue.add(stringRequest);

    }
    void addRecord(String style,String singer){
        String url= MainActivity.ip+"/record/add";
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        // 处理响应
                        String s=response;
                        Log.d("***********",s.toString());
                        if(s.toString().equals("success")){
//                            Toast.makeText(PlayMusic.this, "新增成功", Toast.LENGTH_SHORT).show();
//                            finish();
                        }else{
                            //Toast.makeText(PlayMusic.this, "新增失败!", Toast.LENGTH_SHORT).show();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        // 处理错误
                        Log.d("--------",error.getMessage().toString());
                        //Toast.makeText(PlayMusic.this, "新增失败", Toast.LENGTH_SHORT).show();
                    }
                }) {
            @Override
            protected Map<String, String> getParams() {

                Map<String, String> params = new HashMap<>();
                params.put("user", MainActivity.user.getName());
                params.put("style",style);
                params.put("singer", singer);
                params.put("songId", now_id);
                return params;
            }
        };
        MainActivity.requestQueue.add(stringRequest);
    }








    Handler myhandler=new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message message) {
            if(message.what==1){
                String data_=message.getData().getString("data");
                Log.d("Handler =",data_);
                Toast.makeText(PlayMusic.this, "下载完成", Toast.LENGTH_SHORT).show();
            }
            return false;
        }
    });

    void begin(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                String jsonResult = setApi();
                Log.d("数据：",jsonResult);
                Message message=Message.obtain();
                Bundle bundle=new Bundle();
                bundle.putString("data",jsonResult);
                message.setData(bundle);
                message.what=1;
                myhandler.sendMessage(message);
            }
        }).start();
    }

    String setApi(){
        try{
            String url1="http://47.93.14.182:8080/workspace/music/"
                    +now_id+".mp3";
            URL url=new URL(url1 );
            HttpURLConnection connection = (HttpURLConnection)url.openConnection();
            if(connection.getResponseCode()==200){
                InputStream inputStream = connection.getInputStream();
                // 创建文件输出流
                File internalDir = getApplicationContext().getFilesDir();
                File outputFile = new File(internalDir, now_id+".mp3");

                try (FileOutputStream fos = new FileOutputStream(outputFile)) {
                    // 读取并写入数据
                    byte[] buffer = new byte[80000];
                    int len;
                    while ((len = inputStream.read(buffer)) != -1) {
                        fos.write(buffer, 0, len);
                    }
                    fos.flush(); // 可选，因为try-with-resources会自动关闭流并刷新
                    // 可以在这里添加逻辑来通知用户下载完成

                }
                inputStream.close();
                connection.disconnect();
                return "1";
            }
        }catch (Exception e){
            e.printStackTrace();
            return  e.toString();
        }
        return "0";
    }


}